import { createRouter, createWebHashHistory } from "vue-router";
import { clearAllPending } from "@/api/http/request";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import baseRoutes from "./base";

const publicRouters = ["/login", "/error/403", "/error/404"];

const router = createRouter({
  history: createWebHashHistory(),
  routes: baseRoutes
});

router.beforeEach((to, from, next) => {
  NProgress.start();

  //清除所有无效请求，防止数据污染(结合axios使用)
  clearAllPending();

  document.title = `${to.meta.title} - ${import.meta.env.VITE_APP_NAME}`;

  const userStore = useUserStore();
  if (userStore.token != "") {
    if (to.path === "/login") {
      next({ path: "/home" });
    } else {
      if (userStore.roles.length === 0) {
        userStore
          .getUserInfo()
          .then(() => {
            next({ ...to, replace: true });
          })
          .catch(() => {
            userStore.logout().then(() => {
              next({ path: "/login" });
            });
          });
      } else {
        next();
      }
    }
  } else {
    if (publicRouters.indexOf(to.path) !== -1) {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});

router.afterEach(() => {
  NProgress.done();
  window.scrollTo(0, 0);
});

export default router;
